﻿using System.Collections.Generic;
using System.Linq;
using System.Web.Mvc;

using DomainModel.Abstract;
using DomainModel.Concrete;
using DomainModel.Entities;
using WebCore.Helpers;
using WebCore.Attributes;
using WebCore;
using System;

namespace WebController.Controllers
{
    public class RateController : _baseController
    {
        private readonly IRatesRepository _ratesRepository;

        public RateController()
        {
            _ratesRepository = new RatesRepository();
        }

        [AcceptVerbs(HttpVerbs.Get)]
        [CustomAuthorize(Roles = WebRoles.User | WebRoles.Admin)]
        public ActionResult AddEventRate(int eventID, string returnURL)
        {
            var rateObject = _ratesRepository.GetByEventIDAndUserID(eventID, _user.UserID);

            // make sure this user has not rated this event
            if (rateObject == null)
            {
                var item = new Rate();
                item.EventID = eventID;
                item.UserID = _user.UserID;
                item.DateCreated = DateTime.Now;

                _ratesRepository.Save(item);

                // remove cache
                EventHelper.RemoveAllEventCache();
            }

            return  ReturnURL(returnURL);

        }

        [AcceptVerbs(HttpVerbs.Get)]
        [CustomAuthorize(Roles = WebRoles.User | WebRoles.Admin)]
        public ActionResult RemoveEventRate(int eventID, string returnURL)
        {
            var item = _ratesRepository.GetByEventIDAndUserID(eventID, _user.UserID);

            // make sure the user has rated this event
            if (item != null)
            {
                _ratesRepository.DeleteByEventIDAndUserID(item);

                // remove cache
                EventHelper.RemoveAllEventCache();
            }
            return ReturnURL(returnURL);
        }

        //TODO: duplicates
         private ActionResult ReturnURL(string returnURL)
        {
            if (!string.IsNullOrEmpty(returnURL))
            {
                return Redirect(returnURL);
            }
            else
            {
                return RedirectToAction("Index", "Event");
            }
        }

    }
}
